package client.controller;

import java.io.ByteArrayInputStream ;
import java.io.ObjectInputStream ;
import java.net.DatagramPacket ;
import java.net.InetAddress ;
import java.net.MulticastSocket ;

import javax.vecmath.Quat4d ;
import javax.vecmath.Vector3d ;

//Classe recevant les informations par multicast depuis le serveur
public class ReceiverUpdates extends Thread implements Runnable {

    private transient MulticastSocket socketReception ;
    private Universe3DController deportedClient ;
    public void setDeportedClient (Universe3DController deportedClient) {
      this.deportedClient = deportedClient ;
   }

    private String name = new String () ;
    private String vrml = new String ();
    private Vector3d pos = new Vector3d () ;
    private Quat4d quat = new Quat4d () ;

    public ReceiverUpdates (final String nomGroupe, final int portDiffusion) {
        socketReception = null ;
        try {
           InetAddress adresseDiffusion = InetAddress.getByName (nomGroupe) ;
            socketReception = new MulticastSocket (portDiffusion) ;
            socketReception.joinGroup (adresseDiffusion) ;
            socketReception.setLoopbackMode (false) ;
            System.out.println ("socket : " + socketReception.getLocalPort() + " " + socketReception.getInetAddress ()) ;

        } catch (Exception e) {
            e.printStackTrace () ;
        }
    }

    public void recevoir () {
        try {
            byte [] message = new byte [1024] ;
            DatagramPacket paquet = new DatagramPacket (message, message.length) ;
            socketReception.receive (paquet) ;
            ByteArrayInputStream bais = new ByteArrayInputStream (paquet.getData ()) ;
            ObjectInputStream ois = new ObjectInputStream (bais) ;
            name = (String)ois.readObject () ;
            pos = (Vector3d)ois.readObject () ;
            quat = (Quat4d)ois.readObject () ;
            vrml = (String)ois.readObject() ;
        } catch (Exception e) {
            e.printStackTrace () ;
        }
    }


    public void run () {
        while (true) {
            recevoir () ;
            try {
            deportedClient.objectUpdateTransform (name, vrml, pos, quat) ;
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }

}